package com.ayu.wxgzh.ayucyy.Utils;

import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Date;


@Slf4j
@Component
public class AccessTokenUtils{
    /**
     * 微信支付小程序APP ID
     */
    @Value("${wechat-payment.wechat-mini-app.app-id:}")
    String WECHAT_MINI_APP_APP_ID;

    /**
     * 微信支付小程序APP SECRET
     */
    @Value("${wechat-payment.wechat-mini-app.app-secret:}")
    String WECHAT_MINI_APP_APP_SECRET;

    /**
     * 微信AccessToken过期时间
     */
    Integer WECHAT_ACCESS_TOKEN_EXPIRE_SECOND = 7000;

    /**
     * 微信AccessToken
     */
    String wechatAccessToken;

    /**
     * 微信AccessToken生成时间
     */
    Date wechatAccessTokenRequestTime = new Date();

    /**
     * @return 获取AccessToken
     */
    public String getAccessToken() {
        //初始化情况
        Date currentDate = new Date();
        //比较时间大小
        long betweenSeconds = DateUtil.between(wechatAccessTokenRequestTime, currentDate, DateUnit.SECOND);

        if (wechatAccessToken == null || betweenSeconds > WECHAT_ACCESS_TOKEN_EXPIRE_SECOND) {
            //更新AccessToken
            updateAccessToken();
            //更新获取时间
            wechatAccessTokenRequestTime = new Date();
        }

        return wechatAccessToken;
    }

    /**
     * 更新AccessToken
     */
    private void updateAccessToken() {
        JSONObject jsonObject = new JSONObject();
        try {
            String url = "https://api.weixin.qq.com/cgi-bin/token" +
                    "?grant_type=client_credential" +
                    "&appid=" + WECHAT_MINI_APP_APP_ID
                    + "&secret=" + WECHAT_MINI_APP_APP_SECRET;
            String result = HttpUtil.get(url);

            jsonObject = JSON.parseObject(result);
            wechatAccessToken = jsonObject.getString("access_token");
        } catch (Exception exception) {
            exception.printStackTrace();
        }
    }
}
